using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Collections;

namespace miciv
{
    public class XmlListener
    {
        protected CoreContext m_coreContext;
        protected XmlTraverser m_xmlTraverser;
        protected Hashtable m_htblStartTags;
        protected Hashtable m_htblEndTags;

        public XmlListener()
        {
            this.m_htblStartTags = new Hashtable();
            this.m_htblEndTags = new Hashtable();
        }

        virtual public void Initialize(CoreContext _coreContext, XmlTraverser _xmlTraverser)
        {
            this.m_coreContext = _coreContext;
            this.m_xmlTraverser = _xmlTraverser;
        }

        virtual public void Attach()
        {
            this.m_xmlTraverser.StartElement += this.StartElement;
            this.m_xmlTraverser.EndElement += this.EndElement;
        }

        virtual public void Detach()
        {
            this.m_xmlTraverser.StartElement -= this.StartElement;
            this.m_xmlTraverser.EndElement -= this.EndElement;
        }

        virtual public bool Subscribe(string _strName, XmlTraverser.StartElementEventHandler _start, XmlTraverser.EndElementEventHandler _end)
        {
            if ((false == this.m_htblStartTags.ContainsKey(_strName)) && (false == this.m_htblEndTags.ContainsKey(_strName)))
            {
                this.m_htblStartTags.Add(_strName, _start);
                this.m_htblEndTags.Add(_strName, _end);
                return true;
            }
            return false;
        }

        virtual public bool Unsubscribe(string _strName, XmlTraverser.StartElementEventHandler _start, XmlTraverser.EndElementEventHandler _end)
        {
            if ((false != this.m_htblStartTags.ContainsKey(_strName)) && (false != this.m_htblEndTags.ContainsKey(_strName)))
            {
                this.m_htblStartTags.Remove(_strName);
                this.m_htblEndTags.Remove(_strName);
                return true;
            }
            return false;
        }

        virtual protected bool StartElement(string _strName, XmlAttributeCollection _xmlAttributes)
        {
            if (false != m_htblStartTags.ContainsKey(_strName))
            {
                XmlTraverser.StartElementEventHandler heventStart = m_htblStartTags[_strName] as XmlTraverser.StartElementEventHandler;
                return heventStart(_strName, _xmlAttributes);
            }
            return false;
        }

        virtual protected bool EndElement(string _strName)
        {
            if (false != m_htblEndTags.ContainsKey(_strName))
            {
                XmlTraverser.EndElementEventHandler heventEnd = m_htblEndTags[_strName] as XmlTraverser.EndElementEventHandler;
                return heventEnd(_strName);
            }
            return false;
        }
    }
}
